package com.bigben.springbootshiro.controller;


import org.apache.coyote.Response;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @Autowired
    RedisTemplate<Object,Object> redisTemplate;

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello shiro");
        return "index";
    }

    @RequestMapping("/add")
    public String add(){
        return "/user/add";
    }

    @RequestMapping("/update")
    public String update(){
        return "/user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @GetMapping("/Login")
    public String Login(String username,String password,Model model){

        //获取用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登陆数据（令牌）


        UsernamePasswordToken token = new UsernamePasswordToken(username, password);



        //执行登陆方法
        try {
            subject.login(token);
            return "index";

        } catch (AuthenticationException e) {
            model.addAttribute("msg","用户名或密码错误");
            return "login";
        }


    }

    @RequestMapping("/Noauth")
    @ResponseBody
    public String unauthrized(){
        return "页面未授权";
    }

    @RequestMapping("/loginOut")
    public String LoginOut(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return "index";
    }




}
